package com.youedata.modular.controller;

import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youedata.base.pojo.page.LayuiPageFactory;
import com.youedata.base.tips.DCResponse;
import com.youedata.modular.entity.*;
import com.youedata.modular.enums.SuccessFlag;
import com.youedata.modular.model.dto.*;
import com.youedata.modular.service.*;
import com.youedata.util.FastDFSKit;
import com.youedata.util.ToolUtil;
import com.youedata.util.sdkUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 三方接口控制器
 *
 * @author hst
 * @date 2021-06-05 19:25:44
 */
@Slf4j
@Controller
@Api(value = "/api", tags = "三方接口")
@RequestMapping("/api")
public class APIController {

    @Autowired
    private FastDFSKit fastDFSKit;

    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Autowired
    private IGoodsInfoService goodsInfoService;

    @Autowired
    private ISyTravelInfoService syTravelInfoService;

    @Autowired
    private IGivenPublicNoticeService givenPublicNoticeService;

    @Autowired
    private IFeedbackService feedbackService;

    @Autowired
    private IWaterCutOffNoticeInfoService waterCutOffNoticeInfoService;

    @Autowired
    private IWaterMeterRepairInfoService waterMeterRepairInfoService;

    @Value("${rest.GETINITCODE_URL}")
    private String getInitCodeUrl;

    @Value("${rest.GETAUTHCODE_URL}")
    private String getAuthCodeUrl;

    @Value("${rest.GETACCESSTOKEN_URL}")
    private String getAccessTokenUrl;

    @Value("${rest.REFRESHACCESSTOKEN_URL}")
    private String refreshAccessTokenUrl;

    @Value("${rest.CHECKACCESSTOKEN_URL}")
    private String checkAccessTokenUrl;

    @Value("${rest.CHECKREQUESTCODE_URL}")
    private String checkRequestCodeUrl;

    @Value("${rest.GETUSERINFO_URL}")
    private String getUserInfoUrl;

    @Autowired
    private IKeyInfoService keyInfoService;

    /**
     * 分页查询列表
     *
     * @author hst
     * @date 2021-08-05
     */
    @ResponseBody
    @GetMapping("/goodsInfo/list")
    @ApiOperation(value = "射阳农业局分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, defaultValue = "1", paramType = "query", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "limit", value = "每页多少条数据", required = true, defaultValue = "10", paramType = "query", dataType = "int", example = "20")
    })
    public Object list(GoodsInfoDTO goodsInfoDto) {
        GoodsInfo goodsInfo = new GoodsInfo();

        //过滤空字符串
        goodsInfoDto.setName(StringUtils.isEmpty(goodsInfoDto.getName()) ? null : goodsInfoDto.getName());
        goodsInfoDto.setType(StringUtils.isEmpty(goodsInfoDto.getType()) ? null : goodsInfoDto.getType());
        goodsInfoDto.setRegion(StringUtils.isEmpty(goodsInfoDto.getRegion()) ? null : goodsInfoDto.getRegion());

        BeanUtils.copyProperties(goodsInfoDto, goodsInfo);

        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();

        //根据条件查询
        //page.setRecords(this.goodsInfoService.page(page, Wrappers.query(goodsInfo)).getRecords());
        page.setRecords(this.goodsInfoService.queryFuzzySearch(page, goodsInfo));
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 根据主键查询单条详情
     *
     * @author hst
     * @date 2021-08-05
     */
    @ResponseBody
    @PostMapping("/goodsInfo/detail")
    @ApiOperation(value = "射阳农业局根据主键查询单条详情")
    public ResponseData goodsInfoDetail(@RequestParam("id") String id, @RequestParam("countFlag") String countFlag) {

        return ResponseData.success(this.goodsInfoService.detailById(id, countFlag));
    }

    @ResponseBody
    @PostMapping("/givenPublicNotice/detail")
    @ApiOperation(value = "射阳工信局通知公告根据主键查询单条详情")
    public ResponseData detail(@RequestParam("id") String id) {
        GivenPublicNotice givenPublicNotice = this.givenPublicNoticeService.getById(id);
        if (ToolUtil.isNotEmpty(givenPublicNotice)) {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            givenPublicNotice.setCreateTimeStr(dtf.format(givenPublicNotice.getCreateTime()));
        }
        return ResponseData.success(givenPublicNotice);
//        return ResponseData.success(this.givenPublicNoticeService.getById(id));
    }

    @ResponseBody
    @GetMapping("/givenPublicNotice/list")
    @ApiOperation(value = "射阳工信局通知公告分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, defaultValue = "1", paramType = "query", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "limit", value = "每页多少条数据", required = true, defaultValue = "10", paramType = "query", dataType = "int", example = "20")
    })
    public Object list(GivenPublicNoticeDTO givenPublicNoticeDto) {
        GivenPublicNotice givenPublicNotice = new GivenPublicNotice();
        givenPublicNoticeDto.setName(StringUtils.isEmpty(givenPublicNoticeDto.getName()) ? null : givenPublicNoticeDto.getName());
        givenPublicNoticeDto.setType(StringUtils.isEmpty(givenPublicNoticeDto.getType()) ? null : givenPublicNoticeDto.getType());
        BeanUtils.copyProperties(givenPublicNoticeDto, givenPublicNotice);

        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();

        //根据条件查询
//        page.setRecords(this.givenPublicNoticeService.page(page, Wrappers.query(givenPublicNotice)).getRecords());
        //page.setRecords(this.givenPublicNoticeService.queryFuzzySearch(page,givenPublicNotice));
        List<GivenPublicNotice> givenPublicNoticeList = this.givenPublicNoticeService.queryFuzzySearch(page, givenPublicNotice);
        if (ObjectUtils.isNotEmpty(givenPublicNoticeList)) {
            givenPublicNoticeList.stream().map(x -> {
                if (ToolUtil.isNotEmpty(x.getCreateTime())) {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    x.setCreateTimeStr(dtf.format(x.getCreateTime()));
                }
                return x;
            }).collect(Collectors.toList());
        }
        page.setRecords(givenPublicNoticeList);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 根据主键查询单条详情
     *
     * @author hst
     * @date 2021-08-06
     */
    @ResponseBody
    @PostMapping("/syTravelInfo/detail")
    @ApiOperation(value = "射阳文广旅根据主键查询单条详情")
    public ResponseData syTravelInfoDetail(@RequestParam("id") String id, @RequestParam("countFlag") String countFlag) {
        return ResponseData.success(this.syTravelInfoService.detailById(id, countFlag));
    }

    /**
     * 分页查询列表
     *
     * @author hst
     * @date 2021-08-06
     */
    @ResponseBody
    @GetMapping("/syTravelInfo/list")
    @ApiOperation(value = "射阳文广旅分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, defaultValue = "1", paramType = "query", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "limit", value = "每页多少条数据", required = true, defaultValue = "10", paramType = "query", dataType = "int", example = "20")
    })
    public Object list(SyTravelInfoDTO syTravelInfoDto) {
        SyTravelInfo syTravelInfo = new SyTravelInfo();

        //过滤空字符串
        syTravelInfoDto.setName(StringUtils.isEmpty(syTravelInfoDto.getName()) ? null : syTravelInfoDto.getName());

        BeanUtils.copyProperties(syTravelInfoDto, syTravelInfo);

        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();

        String name = syTravelInfoDto.getName();
        //根据条件查询
        //page.setRecords(this.syTravelInfoService.page(page, Wrappers.query(syTravelInfo)).getRecords());
        page.setRecords(this.syTravelInfoService.queryFuzzySearch(page, syTravelInfo));
        return LayuiPageFactory.createPageInfo(page);
    }


    /**
     * 上传文件
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/fastDFS/upload")
    @ApiOperation(value = "上传并返回完整访问地址")
    public ResponseData upload(MultipartFile file) throws IOException {
        return ResponseData.success(fastDFSKit.uploadFile(file));
    }

//    @ResponseBody
//    @PostMapping("/feedbackfrontupload")
//    @ApiOperation(value = "上传并返回完整访问地址")
//    public void frontupload(HttpServletRequest request,@RequestParam(value = "q_name") String name, @RequestParam(value = "contacts") String contacts, @RequestParam(value = "phone") String phone, @RequestParam(value = "content") String content) throws IOException {
//         String sql = "insert into 'feedback'('enterprise_name','contact_people','phone','content') values(?,?,?,?)";
//         jdbcTemplate.update(sql,name,contacts,phone,content);
//
//    }

    /**
     * 新增
     *
     * @author qyy
     * @date 2021-08-08
     */
    @ResponseBody
    @PostMapping("/feedback/addItem")
    @ApiOperation(value = "射阳工信局反馈前端新增")
    public DCResponse<Void> addItem(FeedbackDTO feedbackDto) {
        Feedback feedback = new Feedback();
        BeanUtils.copyProperties(feedbackDto, feedback);
//        feedback.setCreateUser(Long.valueOf(UserHolder.getUserId()));
        feedback.setCreateTime(LocalDate.from(LocalDateTime.now()));
        this.feedbackService.save(feedback);
        return DCResponse.ok(null);
    }

    @ResponseBody
    @GetMapping("/feedback/list")
    @ApiOperation(value = "射阳工信局反馈前端返回数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, defaultValue = "1", paramType = "query", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "limit", value = "每页多少条数据", required = true, defaultValue = "10", paramType = "query", dataType = "int", example = "20")
    })
    public Object list(FeedbackDTO feedbackDto) {
        Feedback feedback = new Feedback();
        feedbackDto.setEnterpriseName(StringUtils.isEmpty(feedbackDto.getEnterpriseName()) ? null : feedbackDto.getEnterpriseName());
//        feedbackDto.setTag(StringUtils.isEmpty(feedback.getTag())?null:feedbackDto.getTag());
        feedbackDto.setSuggestionType(StringUtils.isEmpty(feedback.getSuggestionType()) ? null : feedbackDto.getSuggestionType());
        BeanUtils.copyProperties(feedbackDto, feedback);

        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();

        //根据条件查询
//        page.setRecords(this.feedbackService.page(page, Wrappers.query(feedback)).getRecords());
        page.setRecords(this.feedbackService.queryFuzzySearch(page, feedback));

        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 上传指定尺寸缩略图
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/uploadImageThumbnail")
    @ApiOperation(value = "上传图片且生成缩略图并返回完整访问地址")
    public ResponseData uploadImageThumbnail(MultipartFile file, int width, int height) throws IOException {
        return ResponseData.success(fastDFSKit.uploadImageThumbnail(file, width, height));
    }


    /**
     * 上传指定尺寸缩略图
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @RequestMapping(value = "/ueditor/uploadImageThumbnail")
    @ResponseBody
    public Map ueditorUploadFileSize(MultipartFile upfile) throws IOException {
        return fastDFSKit.ueditorUploadFileSize(upfile, 320, 150);
    }

    /**
     * 根据主键查询单条详情
     *
     * @author hst
     * @date 2021-07-26
     */
    @ResponseBody
    @PostMapping("/waterCutOffNoticeInfo/detail")
    @ApiOperation(value = "根据主键查询单条详情")
    public ResponseData waterCutOffNoticeInfoDetail(@RequestParam("id") String id) {
        WaterCutOffNoticeInfo waterCutOffNoticeInfo = this.waterCutOffNoticeInfoService.getById(id);
        if (ToolUtil.isNotEmpty(waterCutOffNoticeInfo)) {
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            waterCutOffNoticeInfo.setCreateTimeStr(dtf.format(waterCutOffNoticeInfo.getCreateTime()));
        }
        return ResponseData.success(waterCutOffNoticeInfo);
    }

    /**
     * 分页查询列表
     *
     * @author hst
     * @date 2021-07-26
     */
    @ResponseBody
    @GetMapping("/waterCutOffNoticeInfo/list")
    @ApiOperation(value = "分页查询列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, defaultValue = "1", paramType = "query", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "limit", value = "每页多少条数据", required = true, defaultValue = "10", paramType = "query", dataType = "int", example = "20")
    })
    public Object list(WaterCutOffNoticeInfoDTO waterCutOffNoticeInfoDto) {
        WaterCutOffNoticeInfo waterCutOffNoticeInfo = new WaterCutOffNoticeInfo();

        waterCutOffNoticeInfoDto.setType(StringUtils.isEmpty(waterCutOffNoticeInfoDto.getType()) ? null : waterCutOffNoticeInfoDto.getType());

        BeanUtils.copyProperties(waterCutOffNoticeInfoDto, waterCutOffNoticeInfo);

        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();

        String type = waterCutOffNoticeInfoDto.getType();
        //根据条件查询
        //page.setRecords(this.waterCutOffNoticeInfoService.page(page, Wrappers.query(waterCutOffNoticeInfo)).getRecords());
        List<WaterCutOffNoticeInfo> waterCutOffNoticeInfoList = this.waterCutOffNoticeInfoService.queryTypeFuzzy1(page, type);
        if (ObjectUtils.isNotEmpty(waterCutOffNoticeInfoList)) {
            waterCutOffNoticeInfoList.stream().map(x -> {
                if (ToolUtil.isNotEmpty(x.getCreateTime())) {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    x.setCreateTimeStr(dtf.format(x.getCreateTime()));
                }
                return x;
            }).collect(Collectors.toList());
        }
        page.setRecords(waterCutOffNoticeInfoList);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 获取initCode
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @GetMapping("/getInitCode/{keyId}")
    @ApiOperation(value = "获取initCode")
    public ResponseData getInitCode(@PathVariable Integer keyId) {
        ResponseData responseData = null;

        KeyInfo keyInfo = keyInfoService.getById(keyId);
        if (ToolUtil.isEmpty(keyInfo)) {
            return ResponseData.error("查询不到key值！");
        }

        String resultJson = sdkUtil.getInitCode(getInitCodeUrl, keyInfo.getAppId(), keyInfo.getAppKey());
        if (resultJson != null) {
            Map resultMap = JSON.parseObject(resultJson, Map.class);
            if (SuccessFlag.SUCCESS.getCode().equals(resultMap.get("code"))) {
                responseData = ResponseData.success(resultMap.get("data"));
            } else {
                log.error(resultMap.get("msg").toString());
                responseData = ResponseData.error(resultMap.get("msg").toString());
            }
        }
        return responseData;
    }


    /**
     * 校验RequestCode
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/checkRequestCode")
    @ApiOperation(value = "校验RequestCode")
    public ResponseData checkRequestCode(@RequestBody CheckRequestCodeDTO requestCodeDTO) {
        ResponseData responseData = null;

        String authCode = null;
        String accessToken = null;

        KeyInfo keyInfo = keyInfoService.getById(requestCodeDTO.getKeyId());
        if (ToolUtil.isEmpty(keyInfo)) {
            return ResponseData.error("查询不到key值！");
        }


        //获取authCode
        String authCodeJson = sdkUtil.getAuthCode(getAuthCodeUrl, requestCodeDTO.getAppId(), keyInfo.getAppKey());
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(authCodeJson)) {
            Map resultMap = JSON.parseObject(authCodeJson, Map.class);
            if (SuccessFlag.SUCCESS.getCode().equals(resultMap.get("code"))) {
                authCode = JSON.parseObject(resultMap.get("data").toString()).getString("authCode");
                log.info("authcode=========>{}", authCode);
            } else {
                log.error(resultMap.get("msg").toString());
                return ResponseData.error(resultMap.get("msg").toString());
            }
        }

        //获取accesToken
        String accesTokenJson = sdkUtil.getAccessToken(getAccessTokenUrl, requestCodeDTO.getAppId(), authCode);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(accesTokenJson)) {
            Map resultMap = JSON.parseObject(accesTokenJson, Map.class);
            if (SuccessFlag.SUCCESS.getCode().equals(resultMap.get("code"))) {
                accessToken = JSON.parseObject(resultMap.get("data").toString()).getString("accessToken");
                log.info("accessToken=========>{}", accessToken);
            } else {
                log.error(resultMap.get("msg").toString());
                return ResponseData.error(resultMap.get("msg").toString());
            }
        }

        //校验RequestCode
        String resultJson = sdkUtil.checkRequestCode(checkRequestCodeUrl, requestCodeDTO.getAppId(), accessToken, requestCodeDTO.getRequestCode());
        if (resultJson != null) {
            Map resultMap = JSON.parseObject(resultJson, Map.class);
            if (SuccessFlag.SUCCESS.getCode().equals(resultMap.get("code"))) {
                responseData = ResponseData.success(resultMap.get("data"));
            } else {
                responseData = ResponseData.error(resultMap.get("msg").toString());
            }
        }
        return responseData;
    }

    /**
     * 获取用户信息
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/getUserInfo")
    @ApiOperation(value = "获取用户信息")
    public ResponseData getUserByUserAccessToken(@RequestBody GetUserInfoDTO userInfoDTO) {
        ResponseData responseData;
        UserInfoByOpenidDTO userInfoByOpenidDTO = sdkUtil.getUserByUserAccessToken(getUserInfoUrl, userInfoDTO);

        if (ToolUtil.isEmpty(userInfoByOpenidDTO)) {
            log.error("获取用户信息失败！");
            responseData = ResponseData.error("获取用户信息失败！");
        } else {
            responseData = ResponseData.success(userInfoByOpenidDTO);
        }
        return responseData;
    }
}

